package com.nari.ncps.screen.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.CoalSafetyenvAlarm;
import com.nari.ncps.screen.mapper.coal.CoalSafetyenvAlarmMapper;
import com.nari.ncps.screen.service.coal.CoalSafetyenvAlarmService;
import com.nari.ncps.screen.vo.coal.CoalSafetyAlertVO;
import com.nari.ncps.screen.vo.coal.CoalSafetyEnvVO;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全环保告警表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalSafetyenvAlarmServiceImpl extends ServiceImpl<CoalSafetyenvAlarmMapper, CoalSafetyenvAlarm> implements CoalSafetyenvAlarmService {

    @Override
    public List<CoalSafetyAlertVO> getSafetyAlerts(Integer year) {
        // 查询条件
        QueryWrapper<CoalSafetyenvAlarm> queryWrapper = new QueryWrapper<>();
        
        // 如果指定了年份，按年份过滤
        if (year != null) {
            queryWrapper.eq("year", year);
        } else {
            // 默认获取最近的告警数据（比如最近一个月的数据）
            LocalDateTime oneMonthAgo = LocalDateTime.now().minusMonths(1);
            queryWrapper.ge("alarm_time", oneMonthAgo);
        }
        
        // 按告警时间倒序排列，获取最新的告警数据
        queryWrapper.orderByDesc("alarm_time");
        
        // 限制返回数量（比如最多返回10条）
        queryWrapper.last("LIMIT 10");
        
        List<CoalSafetyenvAlarm> alarmList = this.list(queryWrapper);
        
        // 转换为VO对象
        return alarmList.stream().map(entity -> {
            CoalSafetyAlertVO vo = new CoalSafetyAlertVO();
            vo.setAlarmType(entity.getAlarmType());
            
            // 根据告警类型设置告警类型名称
            String alarmTypeName = getAlarmTypeName(entity.getAlarmType());
            vo.setAlarmTypeName(alarmTypeName);
            
            vo.setUnitCode(entity.getOrgCode());
            vo.setUnitName(entity.getOrgName());
            vo.setAlarmTime(entity.getAlarmTime());
            vo.setAlarmInfo(entity.getAlarmInfo());
            vo.setConfirmStatus(entity.getConfirmStatus());
            return vo;
        }).collect(Collectors.toList());
    }
    
    /**
     * 根据告警类型获取告警类型名称
     * @param alarmType 告警类型：0：边坡告警，1：外运告警，2：库存告警
     * @return 告警类型名称
     */
    private String getAlarmTypeName(Integer alarmType) {
        if (alarmType == null) {
            return "未知告警";
        }
        
        switch (alarmType) {
            case 0:
                return "边坡告警";
            case 1:
                return "外运告警";
            case 2:
                return "库存告警";
            default:
                return "未知告警";
        }
    }
    
    @Override
    public CoalSafetyEnvVO getSafetyEnvAlerts(String orgCode) {
        CoalSafetyEnvVO vo = new CoalSafetyEnvVO();
        
        // 根据orgCode查询安全告警数据
        if (orgCode != null && !orgCode.isEmpty()) {
            LocalDate now = LocalDate.now();
            
            // 查询该单位的安全告警
            QueryWrapper<CoalSafetyenvAlarm> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_code", orgCode)
                       .eq("year", now.getYear())
                       .orderByDesc("alarm_time")
                       .last("LIMIT 10");
            
            List<CoalSafetyenvAlarm> alarmList = this.list(queryWrapper);
            
            if (alarmList != null && !alarmList.isEmpty()) {
                // 转换为CoalSafetyEnvVO.AlertItem格式
                List<CoalSafetyEnvVO.AlertItem> alertItems = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                
                for (CoalSafetyenvAlarm alarm : alarmList) {
                    CoalSafetyEnvVO.AlertItem item = new CoalSafetyEnvVO.AlertItem();
                    item.setLocation(alarm.getOrgName());
                    item.setAlertTime(alarm.getAlarmTime() != null ? sdf.format(alarm.getAlarmTime()) : "");
                    // 根据告警类型设置告警等级
                    item.setAlertLevel(getAlarmTypeName(alarm.getAlarmType()));
                    item.setSlopeAlertInfo(alarm.getAlarmInfo());
                    alertItems.add(item);
                }
                vo.setAlertList(alertItems);
            }
        }
        
        return vo;
    }

}
